<template>
  <div class="wrapper">
    <el-dialog
        title="生成配送单"
        v-model="dialogVisible"
        @close="dialogVisible = false"
        :before-close="()=>dialogVisible = false"
    >
      <div class="delivery-page">
        <!-- 步骤条 -->
        <el-steps :active="activeStep" finish-status="success" align-center class="step-wrapper">
          <el-step title="选择车辆"></el-step>
          <el-step title="生成配送单"></el-step>
          <el-step title="通知司机"></el-step>
        </el-steps>

        <!-- 第一步：选择车辆 -->
        <div v-show="activeStep === 0" class="step-content">
          <el-table
              v-loading="loading"
              :data="vehicleList"
              style="width: 100%;
            height: 52vh;"
              ref="tableRef"
              @selection-change="handleSelectionChange"
              border
              size="small"
          >
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column prop="vehicleNo" label="车编号"/>
            <el-table-column prop="vehicleType" label="车型类型"/>
            <el-table-column label="容量">
              <template v-slot="{ row }">
                {{ row.capacity }}{{ row.capacityUnit }}
              </template>
            </el-table-column>
            <el-table-column label="温控区间">
              <template v-slot="{ row }">
                {{
                  row.temperatureNeed ? `${row.temperatureLow} ~ ${row.temperatureHigh} ${row.temperatureUnit}` : '不提供'
                }}
              </template>
            </el-table-column>
            <el-table-column prop="humidityRange" label="湿度区间">
              <template v-slot="{ row }">
                {{
                  row.humidityNeed ? `${row.humidityLow} ~ ${row.humidityHigh} ${row.humidityUnit}` : '不提供'
                }}
              </template>
            </el-table-column>
            <el-table-column prop="driver.driverName" label="车辆负责人"/>
            <el-table-column prop="driver.driverPhone" label="负责人联系方式"/>
          </el-table>


        </div>

        <!-- 第二步：生成配送单 -->
        <el-result
            icon="info"
            title="操作成功"
            subTitle="正在生成配送单..."
            v-show="activeStep === 1 && deliveryList.length === 0"
        >
        </el-result>
        <div v-show="activeStep === 1 && deliveryList.length > 0" class="step-content step2-cards">
          <el-card hover class="card" v-for="(item, index) in deliveryList" :key="index">
            <h3>批次&nbsp;{{ index + 1 }}</h3>
            <p>配送起点&nbsp;&nbsp;<b>{{ item.origin }}</b></p>
            <p>运输车辆&nbsp;&nbsp;<b>{{ item.vehicleNumber }}</b></p>
            <el-link type="primary" @click="openDetail(item)">查看详情</el-link>
          </el-card>
        </div>

        <!-- 第三步：通知司机 -->
        <div v-show="activeStep === 2" class="step-content">
          <div class="success-box">
            <el-result
                icon="success"
                title="操作成功"
                subTitle="正在通知司机..."
            >
            </el-result>
          </div>
        </div>

        <!-- 配送单详情弹窗 -->
        <el-dialog
            v-model="showDetailDialog"
            title="配送单详情"
            width="80%"
            :before-close="handleDialogClose">
          <template #header>
            <div class="detail-dialog-header">
              <button type="text" @click="showDetailDialog = false">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
                     fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                     stroke-linejoin="round" class="feather feather-arrow-left">
                  <line x1="19" y1="12" x2="5" y2="12"></line>
                  <polyline points="12 19 5 12 12 5"></polyline>
                </svg>
                返回
              </button>
              <p style="margin: 0;">配送单详情</p>
            </div>

          </template>
          <div class="detail-container">
            <!-- 左侧信息 -->
            <div class="left-section">
              <p><strong>编号：</strong>{{ detailData?.item?.deliveryId }}</p>

              <!-- 运输详情 -->
              <div class="detail-section" v-if="detailData?.length">
                <div
                    v-for="(info, idx) in detailData"
                    :key="idx"
                    style="margin-bottom: 12px; border: 1px solid #eee; padding: 8px;"
                >
                  <p><strong>发货地：</strong>{{ info.origin }}&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;<b>预计到达时间：</b>{{
                      new Date(info.expectedDeliveryTime).toLocaleDateString()
                    }}
                  </p>
                  <el-table
                      :data="[info]"
                      border
                      size="small"
                      style="margin-top: 5px;"
                  >
                    <el-table-column prop="orderId" label="订单号"/>
                    <el-table-column prop="productNo" label="商品编码"/>
                    <el-table-column prop="productName" label="商品名称"/>
                    <el-table-column prop="productBatch" label="商品批次"/>
                    <el-table-column label="体积">
                      <template v-slot="{ row }">
                        {{ row.delTransportDetail.size }}{{ row.delTransportDetail.volumeUnit }}
                      </template>
                    </el-table-column>
                    <el-table-column label="重量">
                      <template v-slot="{ row }">
                        {{ row.delTransportDetail.weight }}{{ row.delTransportDetail.weightUnit }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

              <!-- 车辆/司机信息 -->
              <div class="detail-section">
                <div class="driver-info-row">
                  <p><strong>车牌号：</strong>{{ detailData.item.vehicleNumber }}</p>
                </div>
              </div>
            </div>

            <!-- 右侧地图 -->
            <div class="right-section">
              <div class="map-placeholder">
                <BMap
                    v-bind="$attrs"
                    ak="bOCY81ir4Y7BewkkoAzxTV62JgzjBEA2"
                    height="100%"
                    :heading="64.5"
                    :tilt="73"
                    :center="center"
                    :zoom="zoom"
                    :minZoom="3"
                    :mapType="type"
                    :enableDragging="mapSetting.enableDragging"
                    :enableInertialDragging="mapSetting.enableInertialDragging"
                    :enableScrollWheelZoom="mapSetting.enableScrollWheelZoom"
                    :enableContinuousZoom="mapSetting.enableContinuousZoom"
                    :enableDoubleClickZoom="mapSetting.enableDoubleClickZoom"
                    :enableKeyboard="mapSetting.enableKeyboard"
                    :enablePinchToZoom="mapSetting.enablePinchToZoom"
                    :enableTraffic="mapSetting.enableTraffic"
                >
                </BMap>
              </div>
            </div>
          </div>

        </el-dialog>

      </div>
      <template #footer>
        <el-button v-show="activeStep > 0" :disabled="activeStep===1" @click="goPrevStep">上一步</el-button>
        <el-button v-show="activeStep < 2" :disabled="activeStep===1 && deliveryList.length===0" type="primary" @click="goNextStep">下一步</el-button>
        <el-button v-show="activeStep === 2" type="primary" @click="finishOperation">完成</el-button>
        <el-button v-show="activeStep < 2" @click="dialogVisible = false">{{ activeStep < 1?"取消":"关闭" }}</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {BMap} from 'vue3-baidu-map-gl';
import {getAllVehicle} from '@/api/delivery/car.js';
import {generateDelivery} from "@/api/delivery/transport.js";
import {getDelivery} from "@/api/delivery/delivery.js";

const props = defineProps({
  selectedOrders: {
    type: Array,
    required: true,
  },
  modelValue: {
    type: Boolean,
    required: true
  },
});

const emit = defineEmits([
    "update:modelValue",
    "success",
]);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});



/** 当前进行到的步骤 (0: 选择车辆, 1: 生成配送单, 2: 通知司机) */
const activeStep = ref(0)
/** 是否显示“查看详情”的弹窗 */
const showDetailDialog = ref(false)
/** 加载状态（可根据需要处理） */
const loading = ref(false)

// 地图中心与缩放级别
const center = ref({lng: 116, lat: 40});
const zoom = ref(15);

// 地图设置
const type = ref('BMAP_NORMAL_MAP');
const mapSetting = ref({
  enableDragging: true,
  enableInertialDragging: true,
  enableScrollWheelZoom: true,
  enableContinuousZoom: true,
  enableDoubleClickZoom: false,
  enableKeyboard: true,
  enablePinchToZoom: true,
  enableTraffic: false,
});

/** 第一步：车辆数据 */
/** 从接口获取车辆列表数据 */
const vehicleList = ref([])


watch(() => props.modelValue, (newVal) => {
  nextTick(() => {
    if (newVal) {
      console.log('Selecting all rows...');
      selectAll();
    } else {
      setTimeout(() => {
        console.log('Resetting active step...');
        activeStep.value = 0;
        deliveryList.value = [];
      }, 500);
    }
  });
});

onMounted(async () => {
  loading.value = true;
  const res = await getAllVehicle();
  vehicleList.value = res.data;
  loading.value = false;
  await nextTick(() => {
    console.log('Selecting all rows...');
    selectAll();
  },);
});

// 引用表格实例
const tableRef = ref(null);

// 已选中行的数据
const selectedRows = ref([]);

// 处理选中变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
  console.log("Selected Rows:", selectedRows.value);
};

// 表格数据加载完成后全选
const selectAll = () => {
  if (tableRef.value && selectedRows.value.length === 0) {
    tableRef.value.toggleAllSelection(); // 调用 Element Plus 的全选方法
  }
};

/** 第二步：配送单列表（卡片） */
const deliveryList = ref([])

/** 点击查看详情时要展示的数据 */
const detailData = ref({
  id: '',
  transportInfo: [],
  driverName: '',
  driverPhone: '',
  carNumber: '',
  temp: '',
  humidity: ''
})


/** 下一步 */
const goNextStep = () => {

  if (activeStep.value < 2) {
    activeStep.value++
  }

  if (activeStep.value === 1) {
    // 生成配送单
    if (selectedRows.value.length === 0) {
      ElMessage.warning('所选车辆不能为空')
      activeStep.value = 0;
      return
    }
    // 调用后端generate方法生成配送单，向后端发送的请求包括selectedOrders和selectedRows
    // selectedOrders是选中的订单，selectedRows是选中的车辆
    // 生成成功后，将生成的配送单数据填充到deliveryList中
    let excludeVehicle = []

    let all = []
    vehicleList.value.forEach((row, index) => {
      all.push(row.vehicleNo)
    })

    let selected = []
    selectedRows.value.forEach((row, index) => {
      selected.push(row.vehicleNo)
    })

    for (let i = 0; i < all.length; i++) {
      if (!selected.includes(all[i])) {
        excludeVehicle.push(all[i])
      }
    }


    let selectedOrders = props.selectedOrders.map(item => item.trackingNumber)
    console.log('excludeVehicle:', excludeVehicle)
    console.log('selectedOrders:', selectedOrders)
    setTimeout(() => {
      generateDelivery("1", selectedOrders, excludeVehicle).then(res => {
        console.log('生成配送单成功:', res);
        if (res.result.length === 0) {
          ElMessage.warning('分配失败：请检查可用车辆数量或运单状态')
          activeStep.value = 0
          return
        }

        deliveryList.value = res.result
        emit('success', res.result)
      }).catch(err => {
        console.error('生成配送单失败:', err)
        ElMessage.error('生成配送单失败')
        activeStep.value = 0
      })
    }, 1500)

  }
}

/** 上一步 */
const goPrevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value--
  }
}

/** 查看详情：模拟赋值弹窗所需的数据 */
const openDetail = async (item) => {
  let res = await getDelivery(item.deliveryId);
  res.item = item
  console.log('获取配送单详情:', res)
  detailData.value = res

  showDetailDialog.value = true
}

/** 关闭弹窗 */
const handleDialogClose = () => {
  showDetailDialog.value = false
}

/** 第三步完成操作 */
const finishOperation = () => {
  activeStep.value = 0 // 重置到第一步
  handleDialogClose();
  dialogVisible.value = false
}
</script>

<style scoped>
.delivery-page {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
}

/* 步骤条外层 */
.step-wrapper {
  margin-bottom: 20px;
}

/* 三个步骤公用容器 */
.step-content {

}

/* 表格底部的按钮组 */
.btn-group {
  margin-top: 20px;
  text-align: center;
}

/* 第二步：卡片列表 */
.step2-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.step2-cards .card {
  border: none;
  border-radius: 12px;
  padding: 12px;
  background-color: #fff;
}

/* 第三步：成功提示 */
.success-box {
  margin: 40px 0;
  text-align: center;
}

.detail-dialog-header {
  display: inline-flex;
  align-items: center;
  --el-font-size-base: 18px;
  font-size: var(--el-font-size-base);
  gap: 5px;
}
.detail-dialog-header button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: var(--el-font-size-base);
  color: #409eff;
  padding: 0;
  margin: 0;
  outline: none;
  transition: color 0.3s;
  display: inline-flex;
  align-items: center;
}

.detail-dialog-header button:hover {
  color: #66b1ff;
}

.detail-dialog-header svg {
  width: 18px;
  height: 18px;
}

.detail-dialog-header>p {
  font-weight: bold;
}

/* 调整详情弹窗内容布局 */
.detail-container {
  display: flex;
  gap: 16px;
  padding: 0 16px;
  height: 100%;
}

.detail-container .left-section {
  flex-basis: 61.8%;
  overflow-y: auto;
}

.detail-container .right-section {
  flex: 1;
  flex-basis: 38.2%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: auto;
  margin: 10px 0;

}

.detail-container .map-placeholder {
  width: 100%;
  height: 100%;
  background: #f2f2f2;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.detail-container .map-placeholder:deep(.anchorBL) {
  display: none;
}

.driver-info-row {
  display: flex;
  gap: 20px; /* 每项之间的间距 */
  align-items: center; /* 垂直居中对齐 */
  flex-wrap: wrap; /* 如果一行内容过多，自动换行 */
}

.driver-info-row p {
  margin: 0;
  white-space: nowrap; /* 防止文字换行 */
}


.wrapper:deep(.el-dialog) {
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 80vh;
  width: 80vw;
  justify-content: space-between;
  padding: var(--el-dialog-padding-primary, 16px) 0;
  overflow: hidden;
}

.wrapper:deep(.el-dialog__header) {
  padding: 16px var(--el-dialog-padding-primary, 16px);
  padding-top: 8px;
}

.wrapper:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: hidden;
}

.wrapper:deep(.el-dialog__footer) {
  padding: 0 var(--el-dialog-padding-primary, 16px);
  padding-top: 16px;
}
</style>

